package com.huajx.cseek.face;

import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class CseekClient {
    private static Logger logger = LoggerFactory.getLogger(CseekClient.class);

    public static void main(String[] args) {
        IoConnector tcpClient = new NioSocketConnector();
        tcpClient.setConnectTimeoutMillis(30000);
        tcpClient.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(
                        new TextLineCodecFactory(
                                Charset.forName("UTF-8"),
                                LineDelimiter.WINDOWS.getValue(),
                                LineDelimiter.WINDOWS.getValue()
                        )
                )
        );
        tcpClient.setHandler(new IoHandlerAdapter() {
            @Override
            public void sessionOpened(IoSession session) throws Exception {
                super.sessionOpened(session);
                logger.info("session is opened");
                session.write("addFace#{}");
            }

            @Override
            public void messageSent(IoSession session, Object message) throws Exception {
                super.messageSent(session, message);
            }

            @Override
            public void messageReceived(IoSession session, Object message) throws Exception {
                super.messageReceived(session, message);
                //服务器返回消息
                logger.info("返回消息 {}", message);
                session.closeNow();
            }

            @Override
            public void sessionClosed(IoSession session) throws Exception {
                super.sessionClosed(session);
                logger.info("tcp client session closed");
                tcpClient.dispose();
            }
        });

        tcpClient.connect(new InetSocketAddress("106.225.144.98", 10003));
    }
}
